﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using MediaMover.Common.TV;
using MediaMover.Data;
using MediaMover.MVVM.Commands;
using Ninject;

namespace MediaMover.MVVM.ViewModels
{
    public class MyShowsViewModel : WorkspaceViewModel
    {
        private TvDb.IAccess _tvdbAccess = new TvDb.Access();
        private Access _dbAccess;
        public ObservableCollection<Show> MyShows { get; set; }
        public string SearchShow { get; set; }

        public MyShowsViewModel(IKernel kernel)
        {
            _dbAccess = kernel.Get<Access>();
            DisplayName = "My Shows";
            MyShows = new ObservableCollection<Show>(_dbAccess.ShowRepository.GetShows());
        }

        #region Commands
        private ICommand _searchCommand;
        public ICommand SearchCommand
        {
            get
            {
                if (_searchCommand == null)
                {
                    _searchCommand = new RelayCommand
                        (
                            param => Search(),
                            param => true
                        );
                }
                return _searchCommand;
            }
        }

        private ICommand _addCommand;
        public ICommand AddCommand
        {
            get
            {
                if (_addCommand == null)
                {
                    _addCommand = new RelayCommand(param => Add(), param => CanAdd);
                }
                return _addCommand;
            }
        } 
        #endregion

        private void Add()
        {
            Show show = _tvdbAccess.LookupSeriesById(SelectedPossibleShow);
            MyShows.Add(show);
            _dbAccess.ShowRepository.Add(show);
            
        }
        private ObservableCollection<Show> _possibleShows = new ObservableCollection<Show>();
        private bool CanAdd
        {
            get { return SelectedPossibleShow != null && MyShows.Where(x=>x.Code == SelectedPossibleShow.Code).ToList().Count == 0; }
        }
        public ObservableCollection<Show> PossibleShows
        {
            get { return _possibleShows; }
            set { _possibleShows = value; }
        }

        public Show SelectedPossibleShow { get; set; }

        private void Search()
        {
            _possibleShows.Clear();
            foreach (var show in _tvdbAccess.LookupSeriesByName(SearchShow))
            {
                _possibleShows.Add(show);    
            }
            
        }
    }
}
